package com.esms.esmsadmin.service;


import com.esms.esmsadmin.entity.AdminEntity;
import com.esms.esmsadmin.mapper.AdminMapper;
import com.esms.esmsadmin.mapper.AdminRoleMapper;
import com.esms.esmsadmin.utils.AdminUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class AdminService implements UserDetailsService {
    @Resource
    AdminMapper adminMapper;
    @Resource
    AdminRoleMapper adminRoleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        AdminEntity adminEntity = adminMapper.loadUserByName(username);
        if(adminEntity == null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        System.out.println(adminMapper.getAdminRolesById());
        adminEntity.setRoles(adminMapper.getAdminRolesById());
        return adminEntity;
    }

    public List<AdminEntity> getAllAdmin(String keywords) {
        return adminMapper.getAllAdmin(AdminUtils.getCurrentAdmin().getId(),keywords);
    }

    public int updateAdmin(AdminEntity admin) {

        return adminMapper.updateByPrimaryKeySelective(admin);
    }

    //事务注解
    @Transactional
    public boolean updateAdminRole(Integer adminId, Integer[] rids) {
        adminRoleMapper.deleteByAdminId(adminId);
        return adminRoleMapper.insertRole(adminId,rids) == rids.length;
    }

    public int deleteAdminById(Integer id) {
        return adminMapper.deleteByPrimaryKey(id);
    }
}
